package com.maycurobj.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maycurobj.domain.maycurDTO.MaycurCustomerDTO;
import com.maycurobj.pojo.AnnualBudget;
import com.maycurobj.service.http.HttpAPIService;
import com.maycurobj.util.NormalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.util.*;

/**
 * crm 获取会议名称
 */
@Service
@Slf4j
public class CrmSerivceImpl {

    @Autowired
    private HttpAPIService httpAPIService;

    @Value("${crm.url}")
    private String CRMURL;

    /**
     * 无参方法：用于获取所有会议名称。
     *
     * @return
     */
    public List<AnnualBudget> getAnnualBudgetList() {
        String url = String.format("%s%s?$filter=new_approval_state ne 0 and statecode eq 0", CRMURL, "/campaigns");
        url = NormalUtil.encodeUrl(url);
        try {
            String ret = httpAPIService.doGetForCrm(url);
            //log.info("请求crm会议字典list：{}", JSONObject.toJSONString(ret));
            JSONObject jsonObject = JSONObject.parseObject(ret);
            JSONArray array = jsonObject.getJSONArray("value");

            List<AnnualBudget> list = array.toJavaList(AnnualBudget.class);
            log.info("返回数量:{}", list.size());

            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 带参方法：用于模糊查找会议名称，并返回查找的会议名称，没有找到返回空值。
     *
     * @param name
     * @return
     */
    public List<AnnualBudget> getAnnualBudgetList(String name) {
        String url = String.format("%s%s?$filter=new_approval_state ne 0 and statecode eq 0", CRMURL, "/campaigns");
        url = NormalUtil.encodeUrl(url);
        try {
            String ret = httpAPIService.doGetForCrm(url);
            //log.info("请求crm会议字典list：{}", JSONObject.toJSONString(ret));
            JSONObject jsonObject = JSONObject.parseObject(ret);
            JSONArray array = jsonObject.getJSONArray("value");

            List<AnnualBudget> list = array.toJavaList(AnnualBudget.class);
            List<AnnualBudget> list1 = new ArrayList<>();
            log.info("返回数量:{}", list.size());
            //循环查找处理list的每个值，如果name不为空，查找list的value是否包含name值。
            for (int i = 0; i < list.size(); i++) {
                if (StringUtils.isNotBlank(name)) {
                    if (list.get(i).getName().contains(name)) {
                        System.out.println(list.get(i).getName());
                        list1.add(list.get(i));
                    }

                }

            }
            //如果name为空，返回所有list，不为空返回查到的list。
            if (StringUtils.isNotBlank(name)) {
                return list1;
            } else {
                return list;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //客户方法

    /**
     * 获取对应工号的crm客户显示信息
     *
     * @param currentPage 当前页
     * @param pageSize
     * @param keyword     关键字
     * @param employeeNo  用户工号
     * @return
     */
    public Map<String, Object> getCrmUserRoleCustomer(Integer currentPage, Integer pageSize, String keyword, String employeeNo) {
        String defaultSystemuserId = "533f0244-79dd-e811-80c9-0050569a1eab";//管理员

        String url = String.format("%s%s?%s%s", CRMURL, "/accounts", getFetchPage(currentPage, pageSize, "account"), "&$select=_ownerid_value,name,statecode,new_erp_num&$filter=statecode eq 0");
        //拼接查询条件
        if (StringUtils.isNotBlank(keyword)) {
            url += " and contains(name,'" + keyword + "')";
        }
        //排序
        url += "&$orderby=createdon desc";
        url = urlEcode(url);

        //获取用户id
        String crmId = null;
        String _crmId = getCrmSystemUserId(employeeNo);
        if (StringUtils.isNotBlank(_crmId)) {
            crmId = _crmId;
        } else {
            crmId = defaultSystemuserId;
        }

        //获取数据
        try {
            String ret = httpAPIService.doGetForCrm(url, crmId, pageSize);
            JSONObject jsonObject = JSONObject.parseObject(ret);
            JSONArray array = jsonObject.getJSONArray("value");
            //转换列表
            List<MaycurCustomerDTO> dtoList = new ArrayList<>();
            convertDto(array, dtoList, currentPage);
            Map<String, Object> returnMap = new HashMap<>();
            returnMap.put("dataList", dtoList);
            returnMap.put("recordsTotal", jsonObject.getIntValue("@odata.count"));
            return returnMap;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取对应工号的crm客户显示信息
     *
     * @param employeeNo
     * @return
     */
    public Map<String,Object> getUserHasCrmRoleCustomer(String employeeNo, JSONObject entity) {
        Map<String, Object> retMap = new HashMap<>();
        String defaultSystemuserId = "533f0244-79dd-e811-80c9-0050569a1eab";//管理员
        String url = String.format("%s%s?%s", CRMURL, "/accounts", "$select=_ownerid_value,name,statecode,new_erp_num&$filter=statecode eq 0");
        url = urlEcode(url);
        //递归查询json所属部门中是否包含营销中心
        Object object=iterateJson(entity.getJSONObject("requestDepartment"),"text");
        if(Objects.isNull(object)){
            return retMap;
        }
        String depText = object.toString();
        boolean containsMarketing = depText.contains("营销中心");
        if (!containsMarketing){
            return retMap;
        }
        log.info("获取到部门-->{}",depText);
        //获取用户id
        String crmId = null;
        String _crmId = getCrmSystemUserId(employeeNo);
        if (StringUtils.isNotBlank(_crmId)) {
            crmId = _crmId;
        } else {
            crmId = defaultSystemuserId;
        }
        //单据中不存在客户信息,即不需要比对 返回true
        List<String> customerList = getCustomerList(entity);
        log.info("customerList:{}", JSONObject.toJSONString(customerList));
        if (customerList.isEmpty()) {
            return retMap;
        }
        //获取数据 同时比较
        try {
            String ret = httpAPIService.doGetForCrm(url, crmId, null);
            JSONObject jsonObject = JSONObject.parseObject(ret);
            JSONArray array = jsonObject.getJSONArray("value");
            //array to map
            Map<String,String> crmCusmap = new HashMap<>();
            for (Object obj : array) {
                JSONObject _json = (JSONObject) obj;
                crmCusmap.put(_json.getString("name"),_json.getString("name"));
            }
            //比较array中是否包含customerName
            for(String listCus:customerList){
                if(!crmCusmap.containsKey(listCus)){
                    retMap.put(listCus,listCus);
                }
            }
            return retMap;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("客户范围存在异常");
            return retMap;
        }
    }

    /**
     * 获取费用中的客户信息
     */
    private List<String> getCustomerList(JSONObject entity) {
        List<String> customerList = new ArrayList<>();
        JSONArray expenseArray = getObjectArray("expenseList", "value", entity);
        if (Objects.isNull(expenseArray) || expenseArray.isEmpty()) {
            //费用空的
            return customerList;
        }
        //整理费用中的客户信息
        for (Object obj : expenseArray) {
            JSONObject _json = JSONObject.parseObject(JSONObject.toJSONString(obj));
            log.info("打印费用中的客户数据---->>>>:{}", _json.toJSONString());
            //包含CF80字段 需要处理,否则不处理
            if (_json.containsKey("CF80")) {
                Object _obj=iterateJson(_json.getJSONObject("CF80"), "text");
                if(Objects.isNull(_obj)){
                    continue;
                }
                String _s = specialStringHandle(_obj.toString());
                if (!_s.contains("公司公共")|| !_s.contains("博圣生物") || !_s.contains("宁波贝生医疗") ||!_s.contains("杭州贝安云科技") || !_s.contains("杭州杰毅麦特医疗器械")) {
                    customerList.add(_s);
                }
            }
        }
        return customerList;
    }


    /**
     * crm调用 分页字符串 不用替换
     */
    private String getFetchPage(int pageIndex, int pageSize, String entity) {
        try {
            String fetchStr = "fetchXml=<fetch page=\"%d\" count=\"%d\"><entity name=\"%s\"></entity></fetch>&$count=true";
            String paramStr = null;
            if (pageIndex == 0) {
                paramStr = String.format(fetchStr, pageIndex + 1, 14, entity);
            } else {
                paramStr = String.format(fetchStr, pageIndex + 1, pageSize, entity);
            }
            return paramStr;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 编码url
     *
     * @param str
     * @return
     */
    private String urlEcode(String str) {
        try {
            String returnStr = new URI(null, str, null).toURL().toString();
            return returnStr;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 获取crm用户id
     */
    private String getCrmSystemUserId(String employeeNo) {
        String str = "";
        String url = CRMURL + "/systemusers?$select=systemuserid&$filter=new_id eq '" + employeeNo + "' and isdisabled eq false";
        url = urlEcode(url);
        try {
            String ret = httpAPIService.doGetForCrm(url).replaceAll("\\\\\"", "").replaceAll("\\\\\"\"", "\"").replaceAll("@odata.etag", "odata_etag");
            JSONObject json = JSON.parseObject(ret);
            JSONArray value = json.getJSONArray("value");
            for (Object obj : value) {
                JSONObject jsonObject = (JSONObject) obj;
                str = jsonObject.getString("systemuserid");

            }
            return str;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 对象装换
     *
     * @param array
     * @param list
     */
    private void convertDto(JSONArray array, List<MaycurCustomerDTO> list, Integer start) {
        if (start == 0) {
            JSONObject _json = new JSONObject();
            _json.put("name", "公司公共");
            _json.put("accountid", "0000");
            _json.put("new_erp_num", "0000");
            array.add(_json);
        }
        for (Object obj : array) {
            MaycurCustomerDTO dto = new MaycurCustomerDTO();
            JSONObject _json = (JSONObject) obj;
            dto.setName(_json.getString("name"));
            dto.setBizCode(_json.getString("accountid"));
            dto.setU8Code(_json.getString("new_erp_num"));
            list.add(dto);
        }

    }

    private JSONArray getObjectArray(String jsonCode, String arrayCode, JSONObject formData) {
        try {
            JSONObject _jsonObject = formData.getJSONObject(jsonCode);
            JSONArray _jsonArray = _jsonObject.getJSONArray(arrayCode);
            return _jsonArray;
        } catch (Exception e) {
            log.info("获取 每刻自定义校验报文 转换list出错jsonCode---{},arrayCode{}", jsonCode, arrayCode);
            return new JSONArray();
        }
    }

    /**
     * 递归查找 json 子元素
     *
     * @param jsonObject
     * @param valueStr
     * @return
     */
    private Object iterateJson(JSONObject jsonObject, String valueStr) {
        try {
            //先判定是不是空的
            if (Objects.isNull(jsonObject)) {
                log.info("需要递归的json对象为空--->>需要查询的叶节点>>", valueStr);
                return null;
            }
            for (String key : jsonObject.keySet()) {
                Object value = jsonObject.get(key);
                if (value instanceof JSONObject) {
                    Object _r = iterateJson((JSONObject) value, valueStr);
                    if (!Objects.isNull(_r)) {
                        return _r;
                    }
                } else {
                    if (key.equals(valueStr)) {
                        return value;
                    }
                }
            }
        } catch (Exception ex) {
            log.info("json递归异常------>>请注意");
            return null;
        }
        return null;
    }

    private String specialStringHandle(String s) {
        try {
            String[] arg = s.split("\\|\\|\\|");
            return arg[arg.length - 1];
        } catch (Exception e) {
            log.info("｜｜｜截取字符串异常");
            return "";
        }
    }

}
